package com.hitqz.robot.driver.netty.client;

import com.hitqz.robot.driver.netty.handler.RobotControllerMessageHandler;
import com.hitqz.robot.driver.netty.protocol.decoder.RobotControllerDecoder;
import com.hitqz.robot.driver.netty.protocol.encoder.RobotControllerEncoder;
import com.hitqz.robot.driver.util.SourceEnum;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author xupkun
 * @date 2023/8/3
 */
@Slf4j
public class RobotControllerClient {

    public static void connect(String host, Integer port, SourceEnum sourceEnum) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();

            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 50)
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024 * 50)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); // 设置连接超时时间

            ChannelFuture future;
            try {
                b.handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) {
                        channel.pipeline().addLast("encoder", new RobotControllerEncoder());
                        channel.pipeline().addLast("decoder", new RobotControllerDecoder());
                        channel.pipeline().addLast(new LengthFieldPrepender(2));
                        channel.pipeline().addLast(new RobotControllerMessageHandler(sourceEnum));
                    }
                });
                future = b.connect(host, port).sync();
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("Interrupted while connecting", e);
            } catch (Exception e) {
                //log.error("Failed to connect to {}:{}, will retry in 5 seconds", host, port, e);
            }
        } finally {
            group.shutdownGracefully().sync();
        }
    }




    //while (true) {
    //    // 标记开始的index
    //    byteBuf.markReaderIndex();
    //    // 读取了协议的开始标志
    //    int head = byteBuf.readByte();
    //    if (head == 0x5A) {
    //        break;
    //    }
    //    byteBuf.resetReaderIndex();
    //    byteBuf.readByte();
    //    // 跳过之后 判断数据长度
    //    if (byteBuf.readableBytes() == 0) {
    //        return;
    //    }
    //}
    //int version = byteBuf.readByte();
    //short sn = byteBuf.readShort();
    //int dataLength = byteBuf.readInt();
    //
    //if (dataLength > byteBuf.readableBytes()) {
    //    log.info("数据量小，回退索引");
    //    byteBuf.resetReaderIndex();
    //    return;
    //}
    //short cmd = byteBuf.readShort();
    //byte[] innerData = new byte[6];
    //byteBuf.readBytes(innerData);
    //byte[] data = new byte[dataLength];
    //byteBuf.readBytes(data);
    //lastRobotDto = new MessageRobotDto(sn, cmd, new String(data, StandardCharsets.UTF_8));
    //list.add(lastRobotDto);



}
